package client

import (
	"crypto/tls"
	"crypto/x509"
	"embed"
	"encoding/pem"
	"fmt"
	"os"
)

// 使用 Go 1.16+ 的 embed 特性替代资源加载
//
//go:embed tls/*.crt
var certAssets embed.FS

func LoadTLSConfig(rootCertPaths []string) (*tls.Config, error) {
	pool := x509.NewCertPool()

	loadCert := func(path string) error {
		// 优先尝试外部文件加载
		if data, err := os.ReadFile(path); err == nil {
			if ok := pool.AppendCertsFromPEM(data); !ok {
				return fmt.Errorf("failed to parse external certificate: %s", path)
			}
			return nil
		}

		// 回退到嵌入资源
		data, err := certAssets.ReadFile("tls/" + path)
		if err != nil {
			return fmt.Errorf("certificate not found: %w", err)
		}

		block, _ := pem.Decode(data)
		if block == nil {
			return fmt.Errorf("invalid PEM format in embedded certificate: %s", path)
		}

		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return fmt.Errorf("failed to parse X.509 certificate: %w", err)
		}

		pool.AddCert(cert)
		return nil
	}

	for _, path := range rootCertPaths {
		if err := loadCert(path); err != nil {
			return nil, fmt.Errorf("certificate loading failed for %q: %w", path, err)
		}
	}

	return &tls.Config{
		RootCAs:            pool,
		MinVersion:         tls.VersionTLS12,
		InsecureSkipVerify: false,
		CurvePreferences: []tls.CurveID{
			tls.X25519,
			tls.CurveP256,
		},
	}, nil
}
